package com.atguigu.ssyx.common.utils;

import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * ClassName: JwtHelper
 * Package: com.atguigu.ssyx.common.utils
 * Description:
 * User: fzykd
 *
 * @Author: LQH
 * Date: 2023-10-02
 * Time: 12:48
 */

public class JwtHelper {

    //过期时间
    private static long tokenExpiration = 365 * 24 * 60 * 60 * 1000;
    //加密密钥
    private static String tokenSignKey = "ssyx";

    //根据userId+userName生成的token字符串
    public static String createToken(Long userId, String userName) {
        String token = Jwts.builder()
                //分组
                .setSubject("ssyx-USER")
                //token 的过期时间
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                //私有部分
                .claim("userId", userId)
                .claim("userName", userName)
                //加密处理
                .signWith(SignatureAlgorithm.HS512, tokenSignKey)
                //压缩
                .compressWith(CompressionCodecs.GZIP)
                .compact();
        return token;
    }

    //根据token解密 得到userId 和 userName
    public static Long getUserId(String token) {
        if (StringUtils.isEmpty(token)){
            return null;
        }

        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        Integer userId = (Integer) claims.get("userId");
        return userId.longValue();
        // return 1L;
    }

    public static String getUserName(String token) {
        if (StringUtils.isEmpty(token)) {
            return "";
        }

        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        return (String) claims.get("userName");
    }

    //删除
    public static void removeToken(String token) {
        //jwttoken无需删除，客户端扔掉即可。
    }

    public static void main(String[] args) {
        String token = JwtHelper.createToken(1L, "admin");
        System.out.println(token);
        System.out.println(JwtHelper.getUserId(token));
        System.out.println(JwtHelper.getUserName(token));
    }
}
